package br.ufpb.di.ppgi.persistencia.query;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.Component;
import br.ufpb.di.ppgi.negocio.modelo.professorExterno.ProfessorExterno;
import br.ufpb.di.ppgi.persistencia.domainstore.DomainStore;
import br.ufpb.di.ppgi.persistencia.iquery.IProfessorExternoQuery;
import br.ufpb.di.ppgi.persistencia.pagination.HibernateQueryPagedList;

@Component
public class ProfessorExternoQuery extends AbstractJPAHibernateQuery implements IProfessorExternoQuery {

	public ProfessorExternoQuery(DomainStore domainStore) {
		super(domainStore);
	}
	
	private Criteria blank() {
		return createCriteria(ProfessorExterno.class);
	}
	
	@Override
	public ProfessorExterno findByEmail(String email) {
		return unique(
			blank().add(Restrictions.eq("email", email))
		);
	}
	
	@Override
	public ProfessorExterno findByCPF(String cpf) {
		return unique(
			blank().add(Restrictions.eq("cpf", cpf))
		);
	}

	public Integer count() {
		return count(blank());
	}
	
	@Override
	public ProfessorExterno get(Long id) {
		return getDomainStore().get(ProfessorExterno.class, id);
	}

	@Override
	public List<ProfessorExterno> listAll() {
		return getDomainStore().list(ProfessorExterno.class);
	}

	@Override
	public HibernateQueryPagedList<ProfessorExterno> paginarByKey(String key) {
		DetachedCriteria dc = DetachedCriteria.forClass(ProfessorExterno.class);
		
		if (key != null && !key.trim().isEmpty())
			dc.add(Restrictions.ilike("nome", key,MatchMode.ANYWHERE))
				.add(Restrictions.ilike("email", key,MatchMode.ANYWHERE))
				.add(Restrictions.ilike("instituicaoDeOrigem", key,MatchMode.ANYWHERE));
				
		return new HibernateQueryPagedList<ProfessorExterno>(dc,session);
	}

	@Override
	public boolean cpfExists(String cpf) {
		return count(
					blank().add(Restrictions.eq("cpf", cpf))
				) > 0;
	}	
}
